// 创建用户相关的数据管理
import { defineStore } from "pinia";
import { login, userInfo, logout } from "@/api/user/login";
import { cloneDeep } from 'lodash';
// 引入类型校验
// import type { loginForm, loginResponseData } from "@/api/user/type";
import type { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import { constantRoute, anyscRoute, anyRoute } from "@/router/route"
import router from "@/router/index";

// 过滤当前用户的需要展示的异步路由
function filterAsyncRoute(anyscRoute: any, routes: any) {
  return anyscRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      // 递归子路由
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  })
}

export let useUserStore = defineStore('User', {
  // state被定义为返回一个初始状态的函数
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      buttons: [],  //存储用户的按钮权限
    }
  },
  actions: {   //使用this访问整个store实例
    // 用户登陆的方法
    async userLogin(data: any) {
      let result: any = await login(data);

      // 登陆成功，本地存储token
      if (result.code == 200) {
        this.token = (result.data as string);
        SET_TOKEN(<string>result.data);
        // 保证当前的async函数返回一个成功的promise
        return 'ok';
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async userInfo() {
      // 获取用户的信息
      let result = await userInfo();

      if (result.code == 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.buttons = result.data.buttons;
        // 异步路由过滤
        let userAsyncRoute = filterAsyncRoute(cloneDeep(anyscRoute), result.data.routes);
        // 路由逻辑：用户登录后，获取异步路由（动态路由），结合本地静态路由和任意路由，形成用户的菜单权限。
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute];
        // 动态添加异步路由
        [...userAsyncRoute, ...anyRoute].forEach((route: any) => {
          router.addRoute(route);
        })

        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    // 清除用户缓存信息
    async userLogout() {
      let result = await logout();
      console.log(result);
      if (result.code == 200) {
        this.token = '';
        this.username = '';
        this.avatar = ''
        REMOVE_TOKEN();
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message));
      }
    }
  },
  getters: {   //推荐使用箭头函数，state作为第一个参数

  }
})